import axios from 'axios'
import { ElMessageBox as MessageBox, ElMessage as Message } from 'element-plus'
import store from '@/store'
import router from '@/router'
import { getToken, removeToken } from '@/utils/auth'
import { UserActionEnum } from '@/store/modules/user/state'

const baseURL = import.meta.env.VITE_ENV === 'development' ? '/api' : import.meta.env.VITE_BASE_URL
// create an axios instance
axios.defaults.timeout = 30000
const service = axios.create({
  // baseURL: "http://172.16.101.241:8003", // url = base url + request url
  baseURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000, // request timeout
})

export const uploadUrl = `${baseURL}/file/upload`
export const token = getToken()

// request interceptor
service.interceptors.request.use(
  (config) => {
    // console.log(config)
    if (store.getters.token) {
      config.headers['Authorization-admin'] = getToken()
      config.headers['Content-Type'] = 'application/json; charset=UTF-8'
      // config.headers['type'] = ' admin'
    }
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// response interceptor
// response interceptor
// response interceptor
// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (response.config.responseType === 'blob') {
      return response.data
    }
    
    if (res.code === 200 || res.code === "200") {
      return res
    } else {
      return res
    }
  },
  (error) => {
    // 安全获取错误信息
    let message = '网络错误'
    if (error.response) {
      const { data, status } = error.response
      if (data && data.message) {
        message = data.message
      } else if (data && data.error) {
        message = data.error
      } else if (status === 401) {
        message = '登录已过期，请重新登录'
      }
    } else if (error.request) {
      message = '请求超时或网络异常'
    } else {
      message = error.message
    }

    Message({
      message,
      type: 'error',
      duration: 5 * 1000,
    })

    return Promise.reject(new Error(message))
  }
)

export default service
